<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理系统 - 商品管理</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <style>
        body {
            padding-top: 56px;
            min-height: 100vh;
            display: flex;
            flex-direction: column;
        }
        .sidebar {
            min-height: calc(100vh - 56px);
            position: fixed;
            top: 56px;
            left: 0;
            width: 200px;
            z-index: 100;
            padding: 20px 0;
            box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
            background-color: #343a40;
        }
        .sidebar .nav-link {
            color: #ddd;
            padding: 0.5rem 1rem;
        }
        .sidebar .nav-link:hover {
            color: #fff;
            background-color: rgba(255, 255, 255, 0.1);
        }
        .sidebar .nav-link.active {
            color: #fff;
            background-color: rgba(255, 255, 255, 0.2);
        }
        .sidebar .nav-link i {
            margin-right: 8px;
        }
        .main-content {
            margin-left: 200px;
            padding: 20px;
            flex: 1;
        }
        .product-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
        <a class="navbar-brand" href="${pageContext.request.contextPath}/admin">
            <i class="fas fa-dumbbell"></i> 体育商城后台
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav ml-auto">
                <li class="nav-item">
                    <a class="nav-link" href="${pageContext.request.contextPath}/" target="_blank">
                        <i class="fas fa-external-link-alt"></i> 访问前台
                    </a>
                </li>
                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown">
                        <i class="fas fa-user-circle"></i> ${adminUser}
                    </a>
                    <div class="dropdown-menu dropdown-menu-right">
                        <a class="dropdown-item" href="${pageContext.request.contextPath}/admin/logout">
                            <i class="fas fa-sign-out-alt"></i> 退出登录
                        </a>
                    </div>
                </li>
            </ul>
        </div>
    </nav>

    <!-- 侧边栏 -->
    <div class="sidebar bg-dark">
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link" href="${pageContext.request.contextPath}/admin">
                    <i class="fas fa-tachometer-alt"></i> 仪表盘
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link active" href="${pageContext.request.contextPath}/admin/products">
                    <i class="fas fa-box"></i> 商品管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="${pageContext.request.contextPath}/admin/categories">
                    <i class="fas fa-tags"></i> 分类管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="${pageContext.request.contextPath}/admin/users">
                    <i class="fas fa-users"></i> 用户管理
                </a>
            </li>
        </ul>
    </div>

    <!-- 主要内容 -->
    <div class="main-content">
        <div class="container-fluid">
            <!-- 标题行 -->
            <div class="row mb-4">
                <div class="col-md-6">
                    <h2 class="mb-1">商品管理</h2>
                    <p class="text-muted">管理所有体育用品商品</p>
                </div>
                <div class="col-md-6 text-right">
                    <button class="btn btn-primary" data-toggle="modal" data-target="#productModal">
                        <i class="fas fa-plus"></i> 添加商品
                    </button>
                </div>
            </div>
            
            <!-- 搜索过滤器 -->
            <div class="row mb-4">
                <div class="col-md-12">
                    <div class="card shadow-sm">
                        <div class="card-body">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="searchName">商品名称</label>
                                        <input type="text" class="form-control" id="searchName" placeholder="输入商品名称">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="searchCategory">商品分类</label>
                                        <select class="form-control" id="searchCategory">
                                            <option value="">全部分类</option>
                                            <c:forEach items="${categories}" var="category">
                                                <option value="${category.id}">${category.name}</option>
                                            </c:forEach>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label for="searchStatus">商品状态</label>
                                        <select class="form-control" id="searchStatus">
                                            <option value="">全部状态</option>
                                            <option value="1">上架</option>
                                            <option value="0">下架</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-3 d-flex align-items-end">
                                    <button class="btn btn-primary btn-block" id="searchBtn">
                                        <i class="fas fa-search"></i> 搜索
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 商品列表 -->
            <div class="row">
                <div class="col-md-12">
                    <div class="card shadow-sm">
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table table-hover">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>图片</th>
                                            <th>名称</th>
                                            <th>价格</th>
                                            <th>库存</th>
                                            <th>分类</th>
                                            <th>状态</th>
                                            <th>操作</th>
                                        </tr>
                                    </thead>
                                    <tbody id="productTableBody">
                                        <tr>
                                            <td colspan="8" class="text-center">正在加载数据...</td>
                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                            
                            <!-- 分页 -->
                            <nav aria-label="Page navigation" class="mt-4">
                                <ul class="pagination justify-content-center" id="pagination">
                                </ul>
                            </nav>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 商品表单模态框 -->
    <div class="modal fade" id="productModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="productModalTitle">添加商品</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="productForm">
                        <input type="hidden" id="productId">
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label for="productName">商品名称 <span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="productName" required>
                            </div>
                            <div class="form-group col-md-6">
                                <label for="productCategory">商品分类 <span class="text-danger">*</span></label>
                                <select class="form-control" id="productCategory" required>
                                    <option value="">选择分类</option>
                                    <c:forEach items="${categories}" var="category">
                                        <option value="${category.id}">${category.name}</option>
                                    </c:forEach>
                                </select>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label for="productPrice">价格 <span class="text-danger">*</span></label>
                                <div class="input-group">
                                    <div class="input-group-prepend">
                                        <span class="input-group-text">￥</span>
                                    </div>
                                    <input type="number" class="form-control" id="productPrice" min="0.01" step="0.01" required>
                                </div>
                            </div>
                            <div class="form-group col-md-6">
                                <label for="productStock">库存 <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" id="productStock" min="0" required>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group col-md-12">
                                <label for="productSubtitle">副标题</label>
                                <input type="text" class="form-control" id="productSubtitle">
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label for="productImage">主图</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="productImage" readonly>
                                    <div class="input-group-append">
                                        <button class="btn btn-outline-secondary" type="button" id="uploadImageBtn">上传</button>
                                    </div>
                                </div>
                                <div class="mt-2" id="previewContainer" style="display: none;">
                                    <img id="imagePreview" src="" class="img-thumbnail" style="max-height: 150px;">
                                </div>
                            </div>
                            <div class="form-group col-md-6">
                                <label>选项</label>
                                <div class="custom-control custom-switch">
                                    <input type="checkbox" class="custom-control-input" id="productIsHot">
                                    <label class="custom-control-label" for="productIsHot">热门商品</label>
                                </div>
                                <div class="custom-control custom-switch mt-2">
                                    <input type="checkbox" class="custom-control-input" id="productIsNew">
                                    <label class="custom-control-label" for="productIsNew">新品</label>
                                </div>
                                <div class="custom-control custom-switch mt-2">
                                    <input type="checkbox" class="custom-control-input" id="productStatus" checked>
                                    <label class="custom-control-label" for="productStatus">上架状态</label>
                                </div>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="form-group col-md-12">
                                <label for="productDetail">商品详情</label>
                                <textarea class="form-control" id="productDetail" rows="5"></textarea>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveProductBtn">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 图片上传模态框 -->
    <div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">上传图片</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="uploadForm" enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="fileInput">选择图片</label>
                            <input type="file" class="form-control-file" id="fileInput" name="file" accept="image/*">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmUploadBtn">上传</button>
                </div>
            </div>
        </div>
    </div>

    <!-- jQuery 和 Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            let currentPage = 1;
            let pageSize = 10;
            let totalPages = 0;
            let isEdit = false;
            
            // 加载商品列表
            function loadProducts(page = 1) {
                currentPage = page;
                
                let url = "${pageContext.request.contextPath}/admin/products/list?pageNum=" + page + "&pageSize=" + pageSize;
                
                // 添加过滤条件
                const name = $('#searchName').val();
                const category = $('#searchCategory').val();
                const status = $('#searchStatus').val();
                
                if (name) url += "&name=" + encodeURIComponent(name);
                if (category) url += "&categoryId=" + category;
                if (status !== "") url += "&status=" + status;
                
                $.get(url, function(res) {
                    console.log("API响应:", res); // 调试信息
                    if (res.code === 200 || res.success === true) {
                        renderProducts(res.data.records || []);
                        renderPagination(res.data.current, res.data.pages);
                        totalPages = res.data.pages;
                    } else {
                        alert("加载商品失败: " + (res.message || res.msg));
                    }
                }).fail(function(jqXHR, textStatus, errorThrown) {
                    console.error("API请求失败:", textStatus, errorThrown);
                    alert("加载数据失败，请检查网络连接或联系管理员");
                });
            }
            
            // 渲染商品列表
            function renderProducts(products) {
                const $tbody = $('#productTableBody');
                $tbody.empty();
                
                if (products.length === 0) {
                    $tbody.html('<tr><td colspan="8" class="text-center">没有找到商品数据</td></tr>');
                    return;
                }
                
                products.forEach(function(product) {
                    const statusBadge = product.status === 1 
                        ? '<span class="badge badge-success">上架</span>' 
                        : '<span class="badge badge-secondary">下架</span>';
                    
                    const imgSrc = product.mainImage || "${pageContext.request.contextPath}/static/images/product-default.jpg";
                    
                    let tr = '<tr>' +
                        '<td>' + product.id + '</td>' +
                        '<td><img src="' + imgSrc + '" class="product-image" alt="' + product.name + '"></td>' +
                        '<td>' + product.name + '</td>' +
                        '<td>￥' + product.price + '</td>' +
                        '<td>' + product.stock + '</td>' +
                        '<td>' + getCategoryName(product.categoryId) + '</td>' +
                        '<td>' + statusBadge + '</td>' +
                        '<td>' +
                            '<button class="btn btn-sm btn-outline-primary edit-btn" data-id="' + product.id + '">' +
                                '<i class="fas fa-edit"></i> 编辑' +
                            '</button> ' +
                            '<button class="btn btn-sm btn-outline-danger delete-btn" data-id="' + product.id + '">' +
                                '<i class="fas fa-trash"></i> 删除' +
                            '</button>' +
                        '</td>' +
                    '</tr>';
                    $tbody.append(tr);
                });
                
                // 绑定编辑按钮事件
                $('.edit-btn').click(function() {
                    const productId = $(this).data('id');
                    editProduct(productId);
                });
                
                // 绑定删除按钮事件
                $('.delete-btn').click(function() {
                    const productId = $(this).data('id');
                    if (confirm('确定要删除这个商品吗？')) {
                        deleteProduct(productId);
                    }
                });
            }
            
            // 渲染分页
            function renderPagination(current, total) {
                const $pagination = $('#pagination');
                $pagination.empty();
                
                if (total <= 1) return;
                
                let startPage = Math.max(1, current - 2);
                let endPage = Math.min(total, current + 2);
                
                // 上一页
                let prevDisabled = current == 1 ? 'disabled' : '';
                $pagination.append(
                    '<li class="page-item ' + prevDisabled + '">' +
                    '<a class="page-link" href="javascript:;" data-page="' + (current - 1) + '">上一页</a>' +
                    '</li>'
                );
                
                // 页码
                for (let i = startPage; i <= endPage; i++) {
                    let active = i == current ? 'active' : '';
                    $pagination.append(
                        '<li class="page-item ' + active + '">' +
                        '<a class="page-link" href="javascript:;" data-page="' + i + '">' + i + '</a>' +
                        '</li>'
                    );
                }
                
                // 下一页
                let nextDisabled = current == total ? 'disabled' : '';
                $pagination.append(
                    '<li class="page-item ' + nextDisabled + '">' +
                    '<a class="page-link" href="javascript:;" data-page="' + (current + 1) + '">下一页</a>' +
                    '</li>'
                );
                
                // 绑定分页点击事件
                $('.page-link').click(function() {
                    if (!$(this).parent().hasClass('disabled')) {
                        const page = $(this).data('page');
                        loadProducts(page);
                    }
                });
            }
            
            // 获取分类名称
            function getCategoryName(categoryId) {
                const category = findCategoryById(categoryId);
                return category ? category.name : '未知分类';
            }
            
            // 根据ID查找分类对象
            function findCategoryById(categoryId) {
                let categories = [];
                <c:forEach items="${categories}" var="category">
                    categories.push({
                        id: ${category.id},
                        name: "${category.name}"
                    });
                </c:forEach>
                
                return categories.find(function(c) { return c.id === categoryId; });
            }
            
            // 编辑商品
            function editProduct(productId) {
                isEdit = true;
                $('#productModalTitle').text('编辑商品');
                
                // 获取商品详情
                $.get("${pageContext.request.contextPath}/admin/products/list", function(res) {
                    if (res.code === 200 || res.success === true) {
                        const products = res.data.records || [];
                        const product = products.find(function(p) { return p.id === productId; });
                        if (product) {
                            // 填充表单
                            $('#productId').val(product.id);
                            $('#productName').val(product.name);
                            $('#productCategory').val(product.categoryId);
                            $('#productPrice').val(product.price);
                            $('#productStock').val(product.stock);
                            $('#productSubtitle').val(product.subtitle);
                            $('#productImage').val(product.mainImage);
                            $('#productDetail').val(product.detail);
                            $('#productIsHot').prop('checked', product.isHot === 1);
                            $('#productIsNew').prop('checked', product.isNew === 1);
                            $('#productStatus').prop('checked', product.status === 1);
                            
                            // 显示图片预览
                            if (product.mainImage) {
                                $('#imagePreview').attr('src', product.mainImage);
                                $('#previewContainer').show();
                            } else {
                                $('#previewContainer').hide();
                            }
                            
                            // 打开模态框
                            $('#productModal').modal('show');
                        } else {
                            alert('找不到该商品');
                        }
                    } else {
                        alert("获取商品失败: " + (res.message || res.msg));
                    }
                });
            }
            
            // 删除商品
            function deleteProduct(productId) {
                $.ajax({
                    url: "${pageContext.request.contextPath}/admin/products/delete/" + productId,
                    type: "POST",
                    success: function(res) {
                        if (res.code === 200 || res.success === true) {
                            alert("删除成功");
                            loadProducts(currentPage);
                        } else {
                            alert("删除失败: " + (res.message || res.msg));
                        }
                    },
                    error: function() {
                        alert("删除失败，服务器错误");
                    }
                });
            }
            
            // 保存商品
            function saveProduct() {
                const product = {
                    name: $('#productName').val(),
                    categoryId: parseInt($('#productCategory').val()),
                    price: parseFloat($('#productPrice').val()),
                    stock: parseInt($('#productStock').val()),
                    subtitle: $('#productSubtitle').val(),
                    mainImage: $('#productImage').val(),
                    detail: $('#productDetail').val(),
                    isHot: $('#productIsHot').is(':checked') ? 1 : 0,
                    isNew: $('#productIsNew').is(':checked') ? 1 : 0,
                    status: $('#productStatus').is(':checked') ? 1 : 0
                };
                
                if (isEdit) {
                    product.id = parseInt($('#productId').val());
                }
                
                $.ajax({
                    url: "${pageContext.request.contextPath}/admin/products/" + (isEdit ? "update" : "add"),
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify(product),
                    success: function(res) {
                        if (res.code === 200 || res.success === true) {
                            alert(isEdit ? "更新成功" : "添加成功");
                            $('#productModal').modal('hide');
                            loadProducts(currentPage);
                        } else {
                            alert((isEdit ? "更新失败: " : "添加失败: ") + (res.message || res.msg));
                        }
                    },
                    error: function() {
                        alert(isEdit ? "更新失败，服务器错误" : "添加失败，服务器错误");
                    }
                });
            }
            
            // 图片上传
            function uploadImage() {
                const formData = new FormData();
                const fileInput = document.getElementById('fileInput');
                
                if (fileInput.files.length === 0) {
                    alert('请选择图片');
                    return;
                }
                
                formData.append('file', fileInput.files[0]);
                
                $.ajax({
                    url: "${pageContext.request.contextPath}/admin/upload/image",
                    type: "POST",
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(res) {
                        if (res.code === 200 || res.success === true) {
                            $('#productImage').val(res.data);
                            $('#imagePreview').attr('src', res.data);
                            $('#previewContainer').show();
                            $('#uploadModal').modal('hide');
                        } else {
                            alert("上传失败: " + (res.message || res.msg));
                        }
                    },
                    error: function() {
                        alert("上传失败，服务器错误");
                    }
                });
            }
            
            // 初始化事件
            
            // 搜索按钮点击
            $('#searchBtn').click(function() {
                loadProducts(1);
            });
            
            // 添加商品按钮点击
            $('#productModal').on('show.bs.modal', function(e) {
                if (!isEdit) {
                    $('#productModalTitle').text('添加商品');
                    $('#productForm').trigger('reset');
                    $('#productId').val('');
                    $('#previewContainer').hide();
                }
            });
            
            // 图片上传按钮点击
            $('#uploadImageBtn').click(function() {
                $('#uploadForm').trigger('reset');
                $('#uploadModal').modal('show');
            });
            
            // 确认上传按钮点击
            $('#confirmUploadBtn').click(function() {
                uploadImage();
            });
            
            // 保存商品按钮点击
            $('#saveProductBtn').click(function() {
                // 表单验证
                if (!$('#productName').val()) {
                    alert('请输入商品名称');
                    return;
                }
                if (!$('#productCategory').val()) {
                    alert('请选择商品分类');
                    return;
                }
                if (!$('#productPrice').val() || parseFloat($('#productPrice').val()) <= 0) {
                    alert('请输入有效的商品价格');
                    return;
                }
                if (!$('#productStock').val() || parseInt($('#productStock').val()) < 0) {
                    alert('请输入有效的库存数量');
                    return;
                }
                
                saveProduct();
            });
            
            // 初始加载
            loadProducts();
        });
    </script>
</body>
</html> 